<?php
/************************************************************************
 Omnitrix - PHP Development Framework
 Copyright (C) 2012-2018 amonest(eastson@outlook.com)

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
************************************************************************/

class omnitrix_html_dropdown extends omnitrix_html_abstract
{
	protected $_id = null;
	protected $_items = array();

	public function __construct()
	{
		$this->_id = otx_html_next_id('dropdown');
	}

	public function add_item($text, $href, $attribs = array())
	{
		$this->_items[] = array(
			'type' => 'item',
			'text' => $text,
			'href' => $href,
			'attribs' => $attribs
		);
		return $this;
	}

	public function add_link($link)
	{
		$this->_items[] = array(
			'type' => 'link',
			'link' => $link
		);
		return $this;
	}

	public function add_divider()
	{
		$this->_items[] = array(
			'type' => 'divider'
		);
		return $this;
	}

	public function get_id()
	{
		return $this->_id;
	}

	public function render_html()
	{
		return $this->_render_dropdown();
	}

	public function render_link($text, $attribs = array())
	{
		return $this->_render_dropdown()
			. otx_html_tag_simple('span', $text, array('data-dropdown' => '#' . $this->_id) + $attribs + array('class' => 'dropdown-link'));
	}

	protected function _render_dropdown()
	{
		$html = otx_html_tag_start('div', array('id' => $this->_id, 'class' => 'dropdown-menu', 'style' => 'display: none;'))
				. otx_html_tag_start('ul');;

		foreach ($this->_items as $item) {
			if ($item['type'] == 'divider') {
				$html .= otx_html_tag_empty('li', array('class' => 'divider'));
			} else if ($item['type'] == 'link') {
				$html .= otx_html_tag_simple('li', $item['link']);
			} else {
				$html .= otx_html_tag_start('li')
					. otx_html_tag_simple('a', $item['text'], array('href' => $item['href']) + $item['attribs'])
					. otx_html_tag_end('li');
			}
		}

		$html .= otx_html_tag_end('ul')
				. otx_html_tag_end('div');
		return $html;
	}
}